package hxy.bytecode.algorithm.aes;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.shiro.crypto.AesCipherService;
import org.apache.shiro.util.ByteSource;

import java.security.Key;

/**
 * 采用AES算法加密
 *
 * @author eric
 */
@Slf4j
public class AesCipherServiceUtil {

    public static KeyValue encrypt(String pass) {

        AesCipherService acs = new AesCipherService();
        Key key = acs.generateNewKey();
        System.out.println(key.getEncoded());

        byte[] byteKey = key.getEncoded();
//      可以是可以自己新建的然后保存
        byteKey = new byte[]{111, 121, -26, 71, 16, -125, 68, 120, 25, 48, -118, 50, -127, 41, -82, 111};

//        加密
        ByteSource encrypt = acs.encrypt(pass.getBytes(), byteKey);
        log.debug("加密后的字符：" + encrypt);

        KeyValue keyValue = new KeyValue();
        keyValue.setKey(byteKey);
        keyValue.setValue(encrypt.toBase64());

        return keyValue;
    }

    public static String decrypt(KeyValue encryptPass) {
        byte[] b = encryptPass.getValue().getBytes();
        Base64 base64 = new Base64();
        b = base64.decode(b);

        AesCipherService acs = new AesCipherService();

//        Input length must be multiple of 16 when decrypting with padded cipher
        ByteSource decrypt = acs.decrypt(b, encryptPass.getKey());
        String originPassword = decodeStr(decrypt.toString());
        log.debug("解密后的字符：" + originPassword);
        return originPassword;
    }

    public static void main(String[] args) {
        KeyValue encrypt = encrypt("1");
        System.out.println("KeyValue:" + encrypt);
        String decrypt = decrypt(encrypt);
        System.out.println(decrypt);
    }

    /**
     * 创建日期2011-4-25上午10:12:38
     * 修改日期
     * 作者：dh *TODO 使用Base64加密算法加密字符串
     * return
     */
    public static String encodeStr(String plainText) {
        byte[] b = plainText.getBytes();
        Base64 base64 = new Base64();
        b = base64.encode(b);
        String s = new String(b);
        return s;
    }

    /**
     * 创建日期2011-4-25上午10:15:11
     * 修改日期
     * 作者：dh	 *TODO 使用Base64加密
     * return
     */
    public static String decodeStr(String encodeStr) {
        byte[] b = encodeStr.getBytes();
        Base64 base64 = new Base64();
        b = base64.decode(b);
        String s = new String(b);
        return s;
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

}

